#include "types.h"
#include "storage.h"
#include "string.h"
 
extern void printk(char *fmt,...);
extern void mmu_remaping(unsigned int pAddr,unsigned int vAddr,unsigned int bytes);
 
// 使用ram模拟的disk的在存储设备指针数组的编号
#define RAM_DISK_NO 0
 
// 使用ram模拟的disk描述体(外部可访问)
sd_t ramDisk;
 
static int RamDiskDoIn(sd_t *pRam,unsigned int offset,void *buf,unsigned int bytes)
{
    if ((pRam == NULL) || (buf == NULL))
    {
        return(ERR_RET);
    }
    if (bytes < (pRam->baseBytes))
    {
        return(ERR_RET);
    }
    int ret = ERR_RET;
    ret = memncpy(buf,(char *)(pRam->vAddr + offset),bytes);
    return(ret);
}
 
static int RamDiskDoOut(sd_t *pRam,unsigned int offset,void *buf,unsigned int bytes)
{
    if ((pRam == NULL) || (buf == NULL))
    {
        return(ERR_RET);
    }
    if (bytes < (pRam->baseBytes))
    {
        return(ERR_RET);
    }
    int ret = ERR_RET;
    ret = memncpy((char *)(pRam->vAddr + offset),buf,bytes);
    return(ret);
}
 
 
int RamDiskInit(void)
{
    int ret = ERR_RET;
    ramDisk.vAddr = 0x40800000;
    ramDisk.storageBytes = 2 * 1024 * 1024;
    ramDisk.baseBytes = 1;
    ramDisk.DoIn = RamDiskDoIn;
    ramDisk.DoOut = RamDiskDoOut;
    // printk("ramDisk.vAddr:%a\n",ramDisk.vAddr);
    mmu_remaping(0x30800000,0x40800000,ramDisk.storageBytes);
    ret = StorageRegister(&ramDisk,RAM_DISK_NO);
    return(ret);
}
 
int RamDiskRead(unsigned int offset,void *buf,unsigned int bytes)
{
    if (buf == NULL)
    {
        return(ERR_RET);
    }
    int ret = ERR_RET;
    ret = ramDisk.DoOut(&ramDisk,offset,buf,bytes);
    return(ret);
}
 
int RamDiskWrite(unsigned int offset,void *buf,unsigned int bytes)
{
    if (buf == NULL)
    {
        return(ERR_RET);
    }
    int ret = ERR_RET;
    ret = ramDisk.DoIn(&ramDisk,offset,buf,bytes);
    return(ret);
}
 
void RamDiskTest(void)
{
    int ret = ERR_RET;
    ret = RamDiskInit();
    if (ret != SUC_RET)
    {
        printk("RamDiskInit error\n");
        return;
    }
    printk("RamDiskInit success\n");
 
    char buf[64];
    ret = RamDiskRead(0,buf,64);
    if (ret != SUC_RET)
    {
        printk("RamDiskRead error\n");
        return;
    }
    printk("read buf:%s\n",buf);
    
    // char *s = "hello_ramdisk";
    // ret = memncpy(s,buf,13);
    // if (ret != SUC_RET)
    // {
    //     printk("memcpy error\n");
    //     return;
    // }
    // ret = RamDiskWrite(0,buf,64);
    // if (ret != SUC_RET)
    // {
    //     printk("RamDiskWrite error\n");
    //     return;
    // }
    // ret = RamDiskRead(0,buf,64);
    // if (ret != SUC_RET)
    // {
    //     printk("RamDiskRead error\n");
    //     return;
    // }
    // printk("read:%s\n",buf);
}